#include "tcp_socket.hpp"
#include<stdio.h>
//多线程实现 TCP 通信
//

void* entry_function(void* arg)
{
  //线程入口函数
  TcpSocket* new_socket=(TcpSocket*)arg;
  //处理数据收发信息
  while(1){
    //接收数据
    std::string buf;
    bool ret = new_socket->Recv(&buf);
    if(ret==false){
      printf("recv error!\n");
      new_socket->Close();
      break;
    }
    std::cout<<"client say: "<<buf<<std::endl;

    //发送数据
    buf.clear();
    std::cout<<"server say: ";
    fflush(stdout);
    std::cin>>buf;
    ret=new_socket->Send(buf);
    if(ret==false){
      printf("send error!\n");
      new_socket->Close();
      break;
    }
  }  
  delete new_socket;
  return NULL;
}
void create_worker(TcpSocket* new_socket)
{
  //创建线程
  pthread_t tid;
  int ret=pthread_create(&tid,NULL,entry_function,(void*)new_socket);
  if(ret<0){
    printf("pthread_create error!\n");
    new_socket->Close();
    delete new_socket;   //释放空间----------防止内存泄漏
    return;
  }
  //新城创建成功则自动调用县城入口函数实现数据处理
  pthread_detach(tid);   //不关心线程退出信息--------线程分离
  return;
}

int main(int argc,char* argv[])
{
  if(argc!=3){
    std::cout<<"./tcp_srv2 192.168.75.128 9000";
    return -1;
  }
  std::string cip=argv[1];
  uint16_t cport=std::stoi(argv[2]);

  TcpSocket srv_sock;

  //创建套接字
  assert(srv_sock.Socket());

  //绑定地址信息
  assert(srv_sock.Bind(cip,cport));
  //进行监听
  assert(srv_sock.Listen());
  
  while(1){
  //循环建立新连接
  //创建多线程进行循环收发数据
    TcpSocket* newsock=new TcpSocket;
    std::string cli_ip;
    uint16_t cli_port;
    bool ret = srv_sock.Accept(newsock,&cli_ip,&cli_port);
    if(ret==false)
    {
      //建立连接失败，继续处理下一个连接
      continue;
    }
    //连接成功
    std::cout<<"accept success! --- "<<"client : "<<cli_ip<<":"<<cli_port<<std::endl;
    //创建多个线程来实现数据处理
    create_worker(newsock);
  }


  //关闭套接字
  srv_sock.Close();
  return 0;
}
